package org.example.casemodule.service.impl;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.example.casemodule.api.UserInfoService;
import org.example.casemodule.dto.CaseQueryDTO;
import org.example.casemodule.dto.UpdateStatusDTO;
import org.example.casemodule.entity.LawyerEntity;
import org.example.casemodule.mapper.LawyerMapper;
import org.example.casemodule.vo.CaseVO;
import org.example.common.config.Result;
import org.example.common.pojo.SysUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.example.casemodule.service.ILegalCaseService;
import org.example.casemodule.entity.LegalCaseEntity;
import org.example.casemodule.mapper.LegalCaseMapper;


import com.mybatisflex.spring.service.impl.ServiceImpl;

import java.util.List;
import java.util.stream.Collectors;
/**
 * 案件表 服务层实现。
 *
 * @author mybatis-flex-helper automatic generation
 * @since 1.0
 */
@Service
@Slf4j
public class LegalCaseServiceImpl extends ServiceImpl<LegalCaseMapper, LegalCaseEntity> implements ILegalCaseService {

    @Autowired
    private LegalCaseMapper legalCaseMapper;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private LawyerMapper lawyerMapper;
    @Override
    public Page<CaseVO> pageList(CaseQueryDTO caseQueryDTO) {
        QueryWrapper queryWrapper = new QueryWrapper();

        // 执行分页查询
        Page<LegalCaseEntity> paginate = legalCaseMapper.paginate(caseQueryDTO.getPage(), caseQueryDTO.getSize(), queryWrapper);

        // 转换为VO对象
        List<LegalCaseEntity> records = paginate.getRecords();
        List<CaseVO> caseVOS = records.stream().map(this::convertToVO).collect(Collectors.toList());

        Page<CaseVO> page = new Page<>();
        page.setRecords(caseVOS);
        page.setTotalRow(paginate.getTotalRow());
        page.setTotalPage(paginate.getTotalPage());
        page.setPageNumber(paginate.getPageNumber());
        page.setPageSize(paginate.getPageSize());

        return page;
    }

    private CaseVO convertToVO(LegalCaseEntity entity) {
        CaseVO vo = new CaseVO();
        BeanUtils.copyProperties(entity, vo);
        vo.setCaseId(entity.getCaseNo());
        vo.setCaseTitle(entity.getTitle());
        vo.setCaseType(entity.getType());
        vo.setStatus(entity.getStatus());
        vo.setCreateTime(entity.getApplyTime());

        SysUser sysUser = userInfoService.getUserInfo(entity.getUserId());
        vo.setApplicantName(sysUser.getRealName());

        LawyerEntity lawyerEntity = lawyerMapper.selectOneById(entity.getLawyerId());

        SysUser sysUser1 = userInfoService.getUserInfo(lawyerEntity.getUserId());
        vo.setLawyerName(sysUser1.getRealName());
        return vo;
    }


    //案件状态变更
    @Override
    public Result updateCaseStatus(UpdateStatusDTO dto) {
        // 根据caseNo查询案件（而不是ID）
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("case_no", dto.getCaseId());
        //查询案件信息
        LegalCaseEntity legalCaseEntity1 = legalCaseMapper.selectOneByQuery(queryWrapper);
        if (legalCaseEntity1 == null) {
            return Result.fail("案件不存在");
        }
        // 记录原始状态
        Object previousStatus =legalCaseEntity1.getStatus();

        //更新案件信息
        LegalCaseEntity legalCaseEntity = new LegalCaseEntity();
       // legalCaseEntity.setCaseNo(dto.getCaseId());这一步错误
        legalCaseEntity.setId(legalCaseEntity1.getId()); // 设置数据库主键
        legalCaseEntity.setStatus(dto.getNewStatus());
        legalCaseEntity.setCloseReason(dto.getChangeReason());
        int update = legalCaseMapper.update(legalCaseEntity);
        if (update > 0) {
//            // 构造返回数据
//            Map<String, Object> data = Map.of(
//                    "caseId",legalCaseEntity1.getCaseNo(), // 使用案件编号而不是ID
//                    "previousStatus", previousStatus,
//                    "currentStatus", dto.getNewStatus()
//            );
            return Result.ok("案件状态变更成功");
        }
        return Result.fail("案件状态变更失败");


    }

    @Override
    public CaseVO getCaseDetail(String caseId) {
        // 1. 查询案件基本信息
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("case_no", caseId);
        LegalCaseEntity caseEntity = legalCaseMapper.selectOneByQuery(queryWrapper);
        if (caseEntity == null) {
            return null; // 或抛异常
        }

        // 2. 构建 CaseVO
        CaseVO vo = new CaseVO();
        vo.setCaseId(caseEntity.getCaseNo());
        vo.setCaseTitle(caseEntity.getTitle());
        vo.setCaseType(caseEntity.getType());
        vo.setStatus(caseEntity.getStatus());
        vo.setCreateTime(caseEntity.getApplyTime());
        vo.setDescription(caseEntity.getDescription());

        // 3. 查询申请人信息（补充）
        SysUser applicant = userInfoService.getUserInfo(caseEntity.getUserId());
        if (applicant != null) {
            vo.setApplicantName(applicant.getRealName());
        }

        // 4. 查询律师信息（补充）
        LawyerEntity lawyer = lawyerMapper.selectOneById(caseEntity.getLawyerId());
        if (lawyer != null) {
            SysUser lawyerUser = userInfoService.getUserInfo(lawyer.getUserId());
            vo.setLawyerName(lawyerUser.getRealName());
        }

        // 5. 返回结果
        return vo;
    }

}
